
<div class="row animate fadeIn">
    <form id="" class="form-horizontal"  method="post">
      <div class="ibox-title" style="border:none;"><h5 style="color: #00afef"><i>Add Meter Reading</i></h5>
        <div class="ibox-tools">    
            <button  id="sads" class="btn btn-sm btn-primary save-btn-tab">Save</button>
            <a id = "cancel_add" class="btn btn-sm btn-outline btn-info cancel-btn-tab">Cancel</a>
        </div>
      </div>
        <div class="ibox-content" id="scan">
            <div class="form-group"><label class="col-lg-3 control-label">Account No:</label> 
                    <div class="col-lg-5">
                        <select style="" id="" class="chosen-select" name="acct_no">
                          <?php foreach ($accounts as $acct) { ?>
                          <option value="<?php echo $acct->account_id; ?>" ><?php echo $acct->acct_num.' - '.$acct->acct_name; ?></option>
                          <?php } ?>
                        </select>
                    </div>
                    <div class="col-lg-1 input-s">
                        <a id = "getPast_btn" class="btn btn-sm btn-outline btn-info">Proceed</a>
                    </div>
            </div>
            <div class="form-group" >
                  <div><label class="col-lg-3 control-label">Due Date :</label>
                      <div class="col-lg-5">
                          <input type="date" name="date_read" class="form-control">
                      </div>
                  </div>
              </div>
              
        </div>


        <div class="ibox-content" id="prevdata">
            <div class="form-inline form-group" >
              <div><label class="col-lg-3 control-label">Last Payment Date :</label>
                  <div class="col-lg-4">
                      <label id="last_pay_date" class="control-label"> -- </label>
                  </div>
              </div>
              <div><label class="col-lg-2 control-label">Last Due Date :</label>
                  <div class="col-lg-2">
                      <label id="last_due_date" class="control-label"> -- </label>
                  </div>
              </div>
            </div>
            <div class="form-inline form-group" >
              <div><label class="col-lg-3 control-label">Last Reading Date :</label>
                  <div class="col-lg-4">
                      <label id="last_read_date" class="control-label"> -- </label>
                  </div>
              </div>
              <div><label class="col-lg-2 control-label">Balance :</label>
                  <div class="col-lg-2">
                      <label id="current_balance" class="control-label"> -- </label>
                  </div>
              </div>
            </div>
            <div class="form-inline form-group" >
                  <div><label class="col-lg-3 control-label">Previous Meter Reading :</label>
                      <div class="col-lg-4">
                          <label id="previous_read" class="control-label"> -- </label>
                      </div>
                  </div>
              </div>
        </div>


        <div class="ibox-content" id="calculate">
            <div>
                <div class="form-group"><label class="col-lg-3 control-label">New Meter Reading</label> 
                    <div class="col-lg-11 input-s">
                        <input type="text" name="new_mtr_read" class="form-control">
                    </div>
                    <div class="col-lg-9 input-s">
                        <a id = "cur_calculate" class="btn btn-sm btn-outline btn-info">Calculate</a>
                    </div>
                </div>
            </div>  
        </div>


        <div class="ibox-content" id="billing">
            <div>
              <div class="form-inline form-group" >
                <div><label class="col-lg-3 control-label">Period From :</label>
                    <div class="col-lg-4">
                        <label id="period_from" class="control-label"></label>
                    </div>
                </div>
                <div><label class="col-lg-2 control-label">Period To :</label>
                    <div class="col-lg-2">
                          <label id="period_to" class="control-label"></label>
                    </div>
                </div>
              </div>
              <div class="form-inline form-group" >
                  <div><label class="col-lg-3 control-label">Billing Date :</label>
                      <div class="col-lg-4">
                          <label id="cur_bill_date" class="control-label"></label>
                      </div>
                  </div>
                  <div><label class="col-lg-2 control-label">Due Date :</label>
                      <div class="col-lg-2">
                            <label id="latest_due_date" class="control-label"></label>
                      </div>
                  </div>
              </div>
              <div class="form-inline form-group" >
                  <div><label class="col-lg-3 control-label">Account No :</label>
                      <div class="col-lg-4">
                          <label id="v_acctNo" class="control-label"> -- </label>
                      </div>
                  </div>
              </div>
              <div class="form-inline form-group" >
                  <div><label class="col-lg-3 control-label">Account Name :</label>
                      <div class="col-lg-4">
                          <label id="v_acctName" class="control-label"> -- </label>
                      </div>
                  </div>
                  <div><label class="col-lg-2 control-label">Address :</label>
                      <div class="col-lg-2">
                            <label id="v_address" class="control-label"> -- </label>
                      </div>
                  </div>
              </div>
              <div class="form-inline form-group" >
                  <div><label class="col-lg-3 control-label">Previous :</label>
                      <div class="col-lg-4">
                          <label id="prev_read" class="control-label"> -- </label>
                      </div>
                  </div>
                  <div><label class="col-lg-2 control-label">Present :</label>
                      <div class="col-lg-2">
                          <label id="pres_read" class="control-label"> -- </label>
                      </div>
                  </div>
              </div>
              <div class="form-inline form-group" >
                  <div><label class="col-lg-3 control-label">Consumed :</label>
                      <div class="col-lg-4">
                          <label id="consumed" class="control-label"> -- </label>
                      </div>
                  </div>
              </div>
              <div class="form-inline form-group" >
                <div class="col-lg-1"></div>
                <table id=""class="col-lg-3 table" style="width: 75%;margin-bottom:0px;">
                  <thead>
                    <tr>
                      <th style="padding:8px;text-align:center;width:20px;">Consumption</th>
                      <th style="padding:8px;text-align:center;">Description</th>
                      <th style="padding:8px;text-align:center;width:110px;">Equal Amount</th>
                    </tr>
                  </thead>
                  <tbody id="consump_sched">
                    
                  </tbody>
                </table> 
              </div>


              <div class="form-inline form-group" >
                  <div><label class="col-lg-8 control-label" style="padding-right:0px;">Sub Total :</label>
                      <div class="col-lg-4">
                          <label id="sub_total" class="control-label" style="margin-left:10px;"> -- </label>
                      </div>
                  </div>
              </div>
              <div class="form-inline form-group" >
                  <div><label class="col-lg-8 control-label" style="padding-right:0px;">Previous Balance :</label>
                      <div class="col-lg-4">
                          <label id="prev_bal" class="control-label" style="margin-left:10px;"> -- </label>
                      </div>
                  </div>
              </div>
              <!--  -->
              <div id="charges_list">

              </div>

              <div class="form-inline form-group" >
                  <div><label class="col-lg-8 control-label" style="padding-right:0px;">TOTAL :</label>
                      <div class="col-lg-4">
                          <label id="cur_total" class="control-label" style="margin-left:10px;"> -- </label>
                      </div>
                  </div>
              </div>

              <div class="form-inline form-group" >
                  <div><label class="col-lg-8 control-label" style="padding-right:0px;">TOTAL DUE :</label>
                      <div class="col-lg-4">
                          <label id="due_total" class="control-label" style="margin-left:10px;"> -- </label>
                      </div>
                  </div>
              </div>
              
              <!-- <div class="form-inline form-group" >
                <div><label class="col-lg-4 control-label"></label>
                  <div class="col-lg-2">
                    <a id = "" class="btn btn-sm btn-outline btn-info">Calculate</a>
                  </div>
              </div>   -->
              <div class="col-lg-7 pull-right">
                    <a id = "submit_bill" class="btn btn-sm btn-outline btn-info">Create Bill Invoice</a>
                  </div>
            </div>  
        </div>    
    </form>
</div>
            
      <script>
  $(document).ready(function(){
  $(".chosen-select").chosen({width:"100%;"});
  $('#prevdata , #calculate ,#billing').hide(); 
  $('input[name=date_read]').val(new Date().toJSON().slice(0,10));

  var name,prev_rdate,prev_read;
  var address;
  var due_date,cur_date,bm,byr;
  var accountID,accountNum,list_id;
  var cur_total,sub_total = 0;
  var current_read,consumed,bill_bal,total_due,max_rate = 0;

      $('#getPast_btn').click(function(){
        $.ajax({
          type  : "POST",
          url   :"<?php echo base_url($this->session->userdata('forajax') . '/getprevious'); ?>",
          dataType  : 'json',
          data : { "acct_id" : $('select[name=acct_no]').val() , "date" : $('input[name=date_read]').val() } ,
          success : function(d){
            if(d == "false"){
              notifymsg("danger",'Already have water bill for this month.');
              $('#prevdata , #calculate ,#billing').hide(); 
              $('input[name=new_mtr_read]').val('');
            }else{
              notifymsg("hide",'');
              $('#last_read_date').html(d.result[0].reading_date);
              $('#last_due_date').html(d.result[0].latest_due_date);
              $('#last_pay_date').html(d.result[0].latest_pay_date);
              $('#current_balance').html(d.result[0].bill_balance);
              $('#previous_read').html(d.result[0].meter_reading);
              due_date    = d.due_date;
              cur_date    = d.current;
              bm          = d.now_month;  byr = d.now_year;
              bill_bal    = d.result[0].bill_balance;
              list_id     = d.result[0].list_id;
              prev_read   = d.result[0].meter_reading;
              prev_rdate  = d.result[0].reading_date;
              name        = d.result[0].name;
              address     = d.result[0].street_address;
              accountNum  = d.result[0].account_number;
              accountID   = d.result[0].account_id;

              $('#latest_due_date').html(due_date);
              $('#cur_bill_date').html(cur_date);
              $('#period_to').html(cur_date);
              $('input[name=new_mtr_read]').removeAttr('readonly');
              $('#prevdata , #calculate').show();
              $('#billing').hide();

            }
          },
                complete: function(data) {
                      $('#getPast_btn').removeAttr('disabled');
                },
                beforeSend: function(){
                      $('#getPast_btn').attr('disabled',true);
                      $('#prevdata , #calculate').hide();
                }
        });
      });

      $('#cur_calculate').click(function(){
          current_read = $('input[name=new_mtr_read]').val();
          if(parseInt(current_read) < parseInt(prev_read)){
            notifymsg("danger",'Current reading must be greater than previous read.');
            $('#billing').hide();
            $('#prevdata').show();
          }
          else {
             notifymsg("success",'Payables Generated');
          consumed = current_read - prev_read;
          sub_total = 0; cur_total = 0;
          $('#v_address').html(address);
          $('#v_acctName').html(name);
          $('#v_acctNo').html(accountNum);
          $('#period_from').html(prev_rdate);
          $('#prev_read').html(prev_read);
          $('#pres_read').html(current_read);
          $('#consumed').html(consumed);
          $('#prev_bal').html(parseFloat(bill_bal).toFixed(2));
          $.ajax({
            type  : "POST",
            url   : "<?php echo base_url($this->session->userdata('forajax') . '/getcharges_rates'); ?>",
            dataType : 'json',
            data  : { "acct_id" : accountID, "consumed" : consumed},
            success : function(e){
    // ------------- RATES --------------
              $('#consump_sched').empty();         
              var trHTML = '';
              var temp1 = consumed;
              var temp2 = consumed;
              console.log(consumed);
              $.each(e.r1, function(i, item) {
                if((temp2 - e.r1[i].usage_qty) <= 0 ){
                  if(e.r1[i].min_flag == 'Y'){
                    console.log('1');
                    var temp_amt = e.r1[i].usage_qty * e.r1[i].rate;
                    trHTML += '<tr><td text-align:right;>' + e.r1[i].usage_qty + '</td><td text-align:right;>' + e.r1[i].description + '</td><td text-align:right;>' + parseFloat(temp_amt).toFixed(2) + '</td></tr>';
                    sub_total = sub_total + temp_amt;
                    max_rate = e.r1[i].rate;
                    return false;
                  }else{
                    console.log('3');
                     var temp_amt = temp1 * e.r1[i].rate;
                     var qty_dis = temp1;
                     if(temp1 < 10){
                      qty_dis = ('0' + temp1).slice(-2);
                     }
                     trHTML += '<tr><td text-align:right;>' + qty_dis + '</td><td text-align:right;>' + e.r1[i].description + '</td><td text-align:right;>' + parseFloat(temp_amt).toFixed(2)  + '</td></tr>';
                     sub_total = sub_total + temp_amt;
                     max_rate = e.r1[i].rate;
                     return false;
                  }
                }else{
                  var temp_deduc = (temp1 - (temp2-e.r1[i].usage_qty));
                  var temp_amt = temp_deduc* e.r1[i].rate;
                  console.log('2' + temp1);
                  temp1 = (temp1 - temp_deduc)
                  trHTML += '<tr><td text-align:right;>' +temp_deduc + '</td><td text-align:right;>' + e.r1[i].description + '</td><td text-align:right;>' + parseFloat(temp_amt).toFixed(2) + '</td></tr>';
                  sub_total = sub_total + temp_amt;
                }
                 //trHTML += '<tr><td text-align:right;>' + e.r1[i].usage_qty + '</td><td text-align:right;>' + e.r1[i].description + '</td><td text-align:right;>' + e.r1[i].rate + '</td></tr>';
              });
              $('#sub_total').html(parseFloat(sub_total).toFixed(2));
              $('#consump_sched').append(trHTML);
    
    // ------------- CHARGES--------------
      $('#charges_list').html('');
            var trHTML2 = '';
            cur_total = sub_total;
          $.each(e.r2, function(i, item) {
                trHTML2 += '<div class="form-inline form-group" ><div><label class="col-lg-8 control-label" style="padding-right:0px;">'+ e.r2[i].description+' :</label><div class="col-lg-4"><label id="sub_total" class="control-label" style="margin-left:10px;">'+ parseFloat(e.r2[i].chg_amount).toFixed(2) +'</label></div></div></div>';
                 //trHTML += '<tr><td text-align:right;>' + e.r1[i].usage_qty + '</td><td text-align:right;>' + e.r1[i].description + '</td><td text-align:right;>' + e.r1[i].rate + '</td></tr>';
                cur_total = parseFloat(cur_total) + parseFloat(e.r2[i].chg_amount);

              });
          $.each(e.r3, function(i, item) {
                if(e.r3[i].discount_amt != null){
                  trHTML2 += '<div class="form-inline form-group" ><div><label class="col-lg-8 control-label" style="padding-right:0px;">Senior Citizen Discount:</label><div class="col-lg-4"><label id="sub_total" class="control-label" style="margin-left:10px;">'+ parseFloat(e.r3[i].discount_amt).toFixed(2) +'</label></div></div></div>';
                 cur_total = parseFloat(cur_total) + parseFloat(e.r3[i].discount_amt);
                }
              });
            $('#charges_list').append(trHTML2);
            $('#cur_total').html(parseFloat(cur_total).toFixed(2));
            total_due = parseFloat(bill_bal) + parseFloat(cur_total);
            $('#due_total').html(parseFloat(total_due).toFixed(2));
            } ,
                complete: function(data) {
                      $('#cur_calculate').removeAttr('disabled');

                },
                beforeSend: function(){
                      $('#cur_calculate').attr('disabled',true);
                }
          });
      
          $('#billing').show();
          $('#prevdata').hide();

          }
           

        
      });


      // var cur_date = "<?php echo date('d-M-y'); ?>"; 
      // var due_date = "<?php echo date('d-M-y' , strtotime('+15 days')); ?>";
      // var bm  = <?php echo date('m'); ?>;
      // var byr = <?php echo date('Y'); ?>;
      $('#submit_bill').click(function(){
        $.ajax({
          type  : "POST",
          url   :"<?php echo base_url($this->session->userdata('forajax') . '/save_read'); ?>",
          dataType  : 'json',
          data : {"id":accountID , "prev_r":prev_read , "prev_d":prev_rdate , "c_read":current_read , "c_date":cur_date , "cons":consumed , "b_date":cur_date , "b_month":('0' + bm).slice(-2) , "b_year":byr , "r_amt":parseFloat(sub_total).toFixed(2) , "bill_bal":parseFloat(bill_bal).toFixed(2) , "total_d":parseFloat(total_due).toFixed(2) , "c_amt":parseFloat(cur_total).toFixed(2) , "due_d":due_date , "p_flag":'Y' , "m_rate":max_rate  } ,
          success : function(d){                                                                                                                                                                                                        
           if(d[0].status == false)
           {
            notifymsg("danger",'Insertion Failed');
           }else{
            notifymsg("success",'Water Bill Added Successfully.');
              $('#cur_calculate').attr('disabled',true);
              $('#getPast_btn').attr('disabled',true);
              $('input[name=new_mtr_read]').attr('readonly',true);
              $('#submit_bill').attr('disabled',true);
              $('#cancel_add').html('Complete');
           }
          },
          beforeSend: function(){
                      $('#cur_calculate').attr('disabled',true);
                      $('#getPast_btn').attr('disabled',true);
                      $('#submit_bill').attr('disabled',true);
          }
        });
      });
    
  





























 /-----------------       ------------------/
                function alert_cancel(){
                              swal({
                                          title: "Are you sure?",
                                          text: "Your work will not be save",
                                          type: "warning",
                                          showCancelButton: true,
                                          confirmButtonColor: "#DD6B55",
                                          confirmButtonText: "Leave",
                                          cancelButtonText: "Stay",
                                          closeOnConfirm: true,
                                          closeOnCancel: true },
                                      function (isConfirm) {
                                          if (isConfirm) {
                                            swal("success");
                                              close_add(); active_search();
                                              notifymsg("hide","hide");
                                          } else {
                                              swal("Cancelled");
                                          }
                                      });
                          }
              $('#addX').click(function(){
                    close_add();        
               });
              $('#cancel_add').click(function () {
                if($('#cancel_add').html() == "Complete"){
                  close_add(); active_search();
                  notifymsg("hide","hide");
                }else{            
                  alert_cancel();
                }
               });
            });
       
</script>
